package com.ruoyi.tableConfig.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.exception.CaptchaException;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.excel.utils.ExcelUtil;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.ruoyi.tableConfig.api.domain.*;
import com.ruoyi.tableConfig.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.mybatis.core.controller.BaseController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 表格权限业务表Controller
 *
 * @author zly
 * @date 2023-06-06
 */
@RestController
@RequestMapping("/roleTable")
public class SysRoleTableController extends BaseController {
    @Autowired
    private ISysRoleTableService sysRoleTableService;
    @Autowired
    private ISysRoleTableColumnService sysRoleTableColumnService;
    @Autowired
    private ISysRoleTableEditConfigService sysRoleTableEditConfigService;
    @Autowired
    private ISysRoleTableEditRulesService sysRoleTableEditRulesService;
    @Autowired
    private ISysRoleTableFormService sysRoleTableFormService;
    @Autowired
    private ISysRoleTableFormItemService sysRoleTableFormItemService;
    @Autowired
    private ISysRoleTablePagerService sysRoleTablePagerService;
    @Autowired
    private ISysRoleTableProxyService sysRoleTableProxyService;
    @Autowired
    private ISysRoleTableToolbarConfigService sysRoleTableToolbarConfigService;

    /**
     * 查询表格权限业务表列表
     */
    @RequiresPermissions("system:roleTable:list")
    @GetMapping("/list")
    public TableDataInfo list(SysRoleTable sysRoleTable) {
        return TableDataInfo.build(sysRoleTableService.selectSysRoleTableList(sysRoleTable));
    }

    /**
     * 查询表格权限业务表分页列表
     */
    @RequiresPermissions("system:roleTable:page")
    @PostMapping("/page")
    public TableDataInfo page(@RequestBody JSONObject ajaxData) {
        return sysRoleTableService.selectSysRoleTablePage(ajaxData.toJavaObject(SysRoleTable.class), ajaxData.toJavaObject(PageQuery.class));
    }

    /**
     * 导出表格权限业务表列表
     */
    @RequiresPermissions("system:roleTable:export")
    @Log(title = "表格权限业务表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRoleTable sysRoleTable) {
        List<SysRoleTable> list = sysRoleTableService.selectSysRoleTableList(sysRoleTable);
        ExcelUtil.exportExcel(list, "表格权限业务表数据", SysRoleTable.class, response);
    }

    /**
     * vxe-table导出表格权限业务表列表
     */
    @RequiresPermissions("system:roleTable:export")
    @Log(title = "表格权限业务表", businessType = BusinessType.EXPORT)
    @PostMapping("/exportVxe")
    public void exportVxe(HttpServletResponse response, @RequestBody JSONObject params) {
        sysRoleTableService.export(response, params);
    }

    /**
     * 获取表格权限业务表详细信息
     */
    @RequiresPermissions("system:roleTable:query")
    @GetMapping(value = "/{roleTableId}")
    public AjaxResult getInfo(@PathVariable("roleTableId") Long roleTableId) {
        return success(sysRoleTableService.selectSysRoleTableByRoleTableId(roleTableId));
    }

    /**
     * 获取表格权限业务表详细信息(批量)
     */
    @RequiresPermissions("system:roleTable:query")
    @GetMapping(value = "/in/{roleTableIds}")
    public AjaxResult getInfos(@PathVariable(value = "roleTableIds", required = true) Long[] roleTableIds) {
        List<SysRoleTable> list = sysRoleTableService.listByIds(Arrays.asList(roleTableIds));
        return AjaxResult.success(list);
    }

    /**
     * 新增表格权限业务表
     */
    @RequiresPermissions("system:roleTable:add")
    @Log(title = "表格权限业务表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysRoleTable sysRoleTable) {
        return toAjax(sysRoleTableService.insertSysRoleTable(sysRoleTable));
    }

    /**
     * 新增表格权限业务表(批量)
     */
    @RequiresPermissions("system:roleTable:add")
    @Log(title = "表格权限业务表", businessType = BusinessType.INSERT)
    @PostMapping(value = {"/saves"})
    public AjaxResult adds(@RequestBody JSONArray jsonArray) {
        if (!sysRoleTableService.saveBatch(JSONObject.parseArray(jsonArray.toJSONString(), SysRoleTable.class))) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 修改表格权限业务表
     */
    @RequiresPermissions("system:roleTable:edit")
    @Log(title = "表格权限业务表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysRoleTable sysRoleTable) {
        return toAjax(sysRoleTableService.updateSysRoleTable(sysRoleTable));
    }

    /**
     * 修改表格权限业务表(批量)
     */
    @RequiresPermissions("system:roleTable:edit")
    @Log(title = "表格权限业务表", businessType = BusinessType.UPDATE)
    @PutMapping(value = {"/modifys"})
    public AjaxResult edits(@Validated @RequestBody JSONArray jsonArray) {
        if (!sysRoleTableService.updateBatchById(JSONObject.parseArray(jsonArray.toJSONString(), SysRoleTable.class))) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 删除表格权限业务表
     */
    @RequiresPermissions("system:roleTable:remove")
    @Log(title = "表格权限业务表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleTableIds}")
    public AjaxResult removes(@PathVariable(value = "roleTableIds", required = true) Long[] roleTableIds) {
        return toAjax(sysRoleTableService.removeByIds(Arrays.asList(roleTableIds)));
    }

    /**
     * 导入模板下载
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil.exportExcel(new ArrayList<>(), "表格权限业务表模板", SysRoleTable.class, response);
    }


    /**
     * 同步菜单数据
     */
    @RequiresPermissions("system:roleTable:syncDb")
    @Log(title = "表格权限业务", businessType = BusinessType.UPDATE)
    @GetMapping("/syncMenu/{roleId}")
    public AjaxResult dataList(@PathVariable("roleId") Long roleId) {
        sysRoleTableService.syncMenu(roleId);
        return success();
    }

    /**
     * 同步数据
     */
    @RequiresPermissions("tableConfig:roleTable:syncDb")
    @Log(title = "表格权限业务", businessType = BusinessType.UPDATE)
    @GetMapping("/synchDb")
    public AjaxResult synchDb(Long roleTableId, Long menuId, Long tableId, Long roleId) {
        sysRoleTableService.synchDb(roleTableId, tableId, roleId, menuId);
        return success();
    }

    /**
     * 强制同步数据
     */
    @RequiresPermissions("tableConfig:roleTable:syncDb")
    @Log(title = "表格权限业务", businessType = BusinessType.UPDATE)
    @GetMapping("/forceSynchDb")
    public AjaxResult forceSynchDb(Long roleTableId, Long menuId, Long tableId, Long roleId) {
        sysRoleTableService.forceSynchDb(roleTableId, tableId, roleId, menuId);
        return success();
    }

    /**
     * 获取表格配置(修改表配置时使用)
     */
    @RequiresPermissions("tableConfig:roleTable:query")
    @GetMapping("/roleTableConfig/{tableId}")
    public AjaxResult getMenuTableConfig(@PathVariable("tableId") Long roleTableId) {
        SysRoleTable sysRoleTable = sysRoleTableService.selectSysRoleTableByRoleTableId(roleTableId);
        List<SysRoleTableColumn> sysRoleTableColumns = sysRoleTableColumnService.selectSysRoleTableColumnByRoleTableId(roleTableId);
        SysRoleTableEditConfig sysRoleTableEditConfig = sysRoleTableEditConfigService.selectSysRoleTableEditConfigByRoleTableId(roleTableId);
        SysRoleTableEditRules sysRoleTableEditRules = new SysRoleTableEditRules();
        sysRoleTableEditRules.setRoleTableId(roleTableId);
        List<SysRoleTableEditRules> selectSysRoleTableEditRulesList = sysRoleTableEditRulesService.selectSysRoleTableEditRulesList(sysRoleTableEditRules);
        SysRoleTableForm sysRoleTableForm = sysRoleTableFormService.selectSysRoleTableFormByRoleTableId(roleTableId);
        List<SysRoleTableFormItem> sysRoleTableFormItemList = new ArrayList<>();
        if (null != sysRoleTableForm && null != sysRoleTableForm.getRoleFormId()) {
            sysRoleTableFormItemList = sysRoleTableFormItemService.selectSysRoleTableFormItemByRoleFormId(sysRoleTableForm.getRoleFormId());
        }

        SysRoleTablePager sysRoleTablePager = sysRoleTablePagerService.selectSysRoleTablePagerByRoleTableId(roleTableId);
        SysRoleTableProxy sysRoleTableProxy = sysRoleTableProxyService.selectSysRoleTableProxyByRoleTableId(roleTableId);
        SysRoleTableToolbarConfig sysRoleTableToolbarConfig = sysRoleTableToolbarConfigService.selectSysRoleTableToolbarConfigByRoleTableId(roleTableId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("table", sysRoleTable);
        jsonObject.put("columns", sysRoleTableColumns);
        jsonObject.put("editConfig", sysRoleTableEditConfig);
        jsonObject.put("editRile", selectSysRoleTableEditRulesList);
        jsonObject.put("form", sysRoleTableForm);
        jsonObject.put("formItem", sysRoleTableFormItemList);
        jsonObject.put("pager", sysRoleTablePager);
        jsonObject.put("proxy", sysRoleTableProxy);
        jsonObject.put("toolbar", sysRoleTableToolbarConfig);
        return success(jsonObject);
    }

    /**
     * 新增功能表格
     */
    @RequiresPermissions("tableConfig:roleTable:add")
    @Log(title = "功能表格", businessType = BusinessType.INSERT)
    @PostMapping("/roleTableConfig")
    @Transactional
    public AjaxResult addMenuTableConfig(@RequestBody JSONObject ajaxData) {
        try {
            SysRoleTable sysRoleTable = JSON.toJavaObject(ajaxData.getJSONObject("table"), SysRoleTable.class);
            List<SysRoleTableColumn> sysRoleTableColumnList = JSONArray.parseArray(JSONArray.toJSONString(ajaxData.get("columns")), SysRoleTableColumn.class);
            SysRoleTableEditConfig sysRoleTableEditConfig = JSON.toJavaObject(ajaxData.getJSONObject("editConfig"), SysRoleTableEditConfig.class);
            List<SysRoleTableEditRules> sysRoleTableEditRulesList = JSONArray.parseArray(JSONArray.toJSONString(ajaxData.get("editRile")), SysRoleTableEditRules.class);
            SysRoleTableForm sysRoleTableForm = JSON.toJavaObject(ajaxData.getJSONObject("form"), SysRoleTableForm.class);
            List<SysRoleTableFormItem> sysRoleTableFormItemList = JSONArray.parseArray(JSONArray.toJSONString(ajaxData.get("formItem")), SysRoleTableFormItem.class);
            SysRoleTablePager sysRoleTablePager = JSON.toJavaObject(ajaxData.getJSONObject("pager"), SysRoleTablePager.class);
            SysRoleTableProxy sysRoleTableProxy = JSON.toJavaObject(ajaxData.getJSONObject("proxy"), SysRoleTableProxy.class);
            SysRoleTableToolbarConfig sysRoleTableToolbarConfig = JSON.toJavaObject(ajaxData.getJSONObject("toolbar"), SysRoleTableToolbarConfig.class);

            sysRoleTableService.updateSysRoleTable(sysRoleTable);
            for (SysRoleTableColumn sysRoleTableColumn : sysRoleTableColumnList) {
                sysRoleTableColumn.setRoleTableId(sysRoleTable.getRoleTableId());
                if (null != sysRoleTableColumn.getColumnId()) {
                    sysRoleTableColumnService.updateSysRoleTableColumn(sysRoleTableColumn);
                } else {
                    sysRoleTableColumnService.save(sysRoleTableColumn);
                }
            }
            sysRoleTableEditConfig.setRoleTableId(sysRoleTable.getRoleTableId());
            if (null != sysRoleTableEditConfig.getEditConfigId()) {
                sysRoleTableEditConfigService.updateSysRoleTableEditConfig(sysRoleTableEditConfig);
            } else {
                sysRoleTableEditConfigService.insertSysRoleTableEditConfig(sysRoleTableEditConfig);
            }
            for (SysRoleTableEditRules sysRoleTableEditRules : sysRoleTableEditRulesList) {
                sysRoleTableEditRules.setRoleTableId(sysRoleTable.getRoleTableId());
                if (null != sysRoleTableEditRules.getEditRulesId()) {
                    sysRoleTableEditRulesService.updateSysRoleTableEditRules(sysRoleTableEditRules);
                } else {
                    sysRoleTableEditRulesService.save(sysRoleTableEditRules);
                }
            }

            sysRoleTableForm.setRoleTableId(sysRoleTable.getRoleTableId());
            Long formId = -1L;
            if (null != sysRoleTableForm.getFormId()) {
                formId = sysRoleTableForm.getFormId();
                sysRoleTableFormService.updateSysRoleTableForm(sysRoleTableForm);
            } else {
                sysRoleTableFormService.insertSysRoleTableForm(sysRoleTableForm);
                formId = (long) sysRoleTableForm.getFormId();
            }
            for (SysRoleTableFormItem sysRoleTableFormItem : sysRoleTableFormItemList) {
                sysRoleTableFormItem.setRoleFormId(formId);
                if (null != sysRoleTableFormItem.getRoleItemId()) {
                    sysRoleTableFormItemService.updateSysRoleTableFormItem(sysRoleTableFormItem);
                } else {
                    sysRoleTableFormItemService.save(sysRoleTableFormItem);
                }
            }

            sysRoleTablePager.setRoleTableId(sysRoleTable.getRoleTableId());
            if (null != sysRoleTablePager.getPagerId()) {
                sysRoleTablePagerService.updateSysRoleTablePager(sysRoleTablePager);
            } else {
                sysRoleTablePagerService.insertSysRoleTablePager(sysRoleTablePager);
            }
            sysRoleTableProxy.setRoleTableId(sysRoleTable.getRoleTableId());
            if (null != sysRoleTableProxy.getProxyId()) {
                sysRoleTableProxyService.updateSysRoleTableProxy(sysRoleTableProxy);
            } else {
                sysRoleTableProxyService.insertSysRoleTableProxy(sysRoleTableProxy);
            }
            sysRoleTableToolbarConfig.setRoleTableId(sysRoleTable.getRoleTableId());
            if (null != sysRoleTableToolbarConfig.getToolbarConfigId()) {
                sysRoleTableToolbarConfigService.updateSysRoleTableToolbarConfig(sysRoleTableToolbarConfig);
            } else {
                sysRoleTableToolbarConfigService.insertSysRoleTableToolbarConfig(sysRoleTableToolbarConfig);
            }
            return success();
        } catch (CaptchaException e) {
            return error();
        }
    }
}
